package com.glsc.ngateway.opmanage.controller.document;


import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.api.common.ex.Result;
import com.glsc.ngateway.common.api.common.utils.JsonUtil;
import com.glsc.ngateway.common.api.flowable.dto.demand.FileType;
import com.glsc.ngateway.common.api.flowable.dto.demand.ReportShowResponse;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.document.DocumentInfo;
import com.glsc.ngateway.opmanage.service.document.DocumentService;
import com.glsc.ngateway.opmanage.utils.FileUtil;
import com.glsc.ngateway.opmanage.utils.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@Api(value = "通用文件上传接口", tags = {"通用文件上传接口"})
@RequestMapping("/api/document")
public class DocumentUploadController {
    private static Logger logger = LoggerFactory.getLogger(DocumentUploadController.class);

    @Resource
    private DocumentService documentService;

    @Resource
    TokenUtil tokenUtil;

    @Value("${commonDocument.downloadUrl}")
    String downloadUrl;


    @PostMapping("/uploadFile")
    @ApiOperation(value = "文件上传", notes = "上传产品档案，不大于100M")
    public PlatformResponse<?> uploadFile(MultipartFile file) throws IOException {
        return documentService.uploadFile(file);
    }

    /**
     * 下载
     *
     * @param docId
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/download")
    @ApiOperation(value = "根据档案Id查询档案字节流", notes = "根据档案Id查询档案字节流")
    public Object getContentById(@ApiParam(required = true, value = "档案ID") @RequestParam Integer docId
            , HttpServletRequest request
            , HttpServletResponse response) throws IOException {

        Assert.isTrue(!(null == docId || docId < 0), "查询档案ID不合法");

        DocumentInfo documentInfoDb = documentService.findById(docId);

        if (null == documentInfoDb || StrUtil.isEmpty(documentInfoDb.getFileName())) {
            return Result.fail("档案不存在或文件名为空");
        }

        String fileName = documentInfoDb.getFileName();
        if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")) {
            response.setContentType("image/png");
        } else {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        }
        OutputStream output = response.getOutputStream();
        byte[] bytes = FileUtil.readByteFromFilePath(documentInfoDb.getFilePath());
        if (null == bytes) {
            output.close();
            return null;
        }
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        int len;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) != -1) {
            output.write(buf, 0, len);
        }
        output.flush();
        output.close();
        return null;
    }


    /**
     * 通用文件预览接口
     *
     * @param docId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/showDoc")
    public PlatformResponse<ReportShowResponse> show(@ApiParam(required = true, value = "档案ID") @RequestParam Integer docId) {

        DocumentInfo documentInfoDb = documentService.findById(docId);

        PlatformResponse<ReportShowResponse> ret = null;
        try {
            String title = documentInfoDb.getFileName();
            String url = downloadUrl + docId;
            String token = tokenUtil.generateToken(JsonUtil.Obj2Str(new ReportShowResponse(title, url, FileType.valueOf(title.substring(title.lastIndexOf(".") + 1)))));

            ReportShowResponse resdata = new ReportShowResponse(title, url, token, FileType.valueOf(title.substring(title.lastIndexOf(".") + 1)));
            ret = PlatformResponse.successData(resdata);
            ret.setFileId(title);
        } catch (Exception e) {
            ret = PlatformResponse.failedMsg(e.getMessage());
        }

        return ret;
    }

    /**
     * 文件预览专用下载接口-无鉴权,前端页面不要使用[后续要优化]
     *
     * @param docId
     * @return
     * @throws IOException
     */
    @GetMapping("/showDoc/download")
    @ApiOperation(value = "文件预览专用下载接口", notes = "文件预览专用下载接口")
    public ResponseEntity<byte[]> getContentById4ShowDoc(@ApiParam(required = true, value = "档案ID") @RequestParam Integer docId) throws IOException {

        Assert.isTrue(!(null == docId || docId < 0), "查询档案ID不合法");

        DocumentInfo documentInfoDb = documentService.findById(docId);

        if (null == documentInfoDb || StrUtil.isEmpty(documentInfoDb.getFileName())) {
            return null;
        }

        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(documentInfoDb.getFilePath()));
        byte[] bytes = new byte[in.available()];
        String imageName = documentInfoDb.getFileName();
        //处理IE下载文件的中文名称乱码的问题
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) attrs).getRequest();
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }


}
